﻿namespace Dissemination.MVC.MVCContrib.Base
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web.Mvc;
    using Microsoft.Practices.Unity;
    using Interfaces;
    using System.ComponentModel;
    using UnityContrib.Interfaces;
    using UnityContrib.Types;

    public class MVCControllerBase : Controller, IControllerBase
    {
        /// <summary>
        /// Gets or sets the logger.
        /// </summary>
        /// <value>The logger.</value>
        private ILoggerFacade _logger;
        [Dependency]
        public ILoggerFacade Logger
        {
            get { return _logger; }
            set {
                // Prevent the following error
                // System.Threading.SynchronizationLockException' occurred in Microsoft.Practices.Unity.DLL
                if (_logger==null || _logger.GetType().ToString()!=value.GetType().ToString())
                    _logger = value; 
            }
        }

        private IUnityContainer _container;

        /// <summary>
        /// Gets or sets the container.  Set by the CustomControllerFactory
        /// </summary>
        /// <value>The container.</value>
        public IUnityContainer Container
        {
            get { return _container; }
            set
            {
                // Don't set if already set
                if (_container != null && _container.GetType().ToString() == value.GetType().ToString())
                    return;

                _container = value;

                // Buildup of MVCControllerBase so that we can
                // have logger and future types
                value.BuildUp(this);

                // We'll have a Logger now that this is built up.
                Logger.Log("ControllerBase::Container (setter) -- Performing Buildup of " + GetType().Name,
                    Category.Debug, Priority.None);

                // The type will be that of the derived class.
                // BuildUp of the parent controller
                value.BuildUp(GetType(), this);

                // Notify controller
                OnContainerSet();
            }
        }

        /// <summary>
        /// Called when [container set].
        /// </summary>
        protected virtual void OnContainerSet()
        {
        }

    }
}
